#!/bin/sh /etc/rc.common
# Copyright (C) 2017 - 2018 OpenWrt.org

START=90

USE_PROCD=1

#PROCD_DEBUG=1

NAME=freeswitch
COMMAND=/usr/bin/$NAME

LOGGER="/usr/bin/logger -p user.err -s -t $NAME --"

start_service() {
  local dir
  local enabled

  local user
  local group

  local log_stderr
  local log_stdout

  local dir_cache
  local dir_db
  local dir_etc=/etc/$NAME
  local dir_localstate=/var/lib/$NAME
  local dir_log
  local dir_recordings
  local dir_run=/var/run/$NAME
  local dir_storage
  local dir_temp

  local options

  config_load $NAME

  config_get_bool enabled general enabled 0
  if [ $enabled -eq 0 ]; then
    $LOGGER service not enabled in /etc/config/$NAME
    exit 1
  fi

  config_get user  general user  $NAME
  config_get group general group $NAME

  config_get_bool log_stderr general log_stderr 1
  config_get_bool log_stdout general log_stdout 1

  config_get dir_cache      directories cache      /tmp/$NAME/cache
  config_get dir_db         directories db         /tmp/$NAME/db
  config_get dir_log        directories log        /tmp/$NAME/log
  config_get dir_recordings directories recordings /tmp/$NAME/recordings
  config_get dir_storage    directories storage    /tmp/$NAME/storage
  config_get dir_temp       directories temp       /tmp/$NAME/temp

  user_exists "$user" || {
    $LOGGER user \""$user"\" does not exist
    exit 1
  }

  group_exists "$group" || {
    $LOGGER group \""$group"\" does not exist
    exit 1
  }

  # do not touch directories that already exist
  # posix shell does not support arrays, hence using awk
  awk \
    -v user="$user" \
    -v group="$group" \
    -v a="$dir_cache" \
    -v b="$dir_db" \
    -v c="$dir_localstate" \
    -v d="$dir_log" \
    -v e="$dir_recordings" \
    -v f="$dir_run" \
    -v g="$dir_storage" \
    -v h="$dir_temp" \
    '
      BEGIN {
        dir[0]=a
        dir[1]=b
        dir[2]=c
        dir[3]=d
        dir[4]=e
        dir[5]=f
        dir[6]=g
        dir[7]=h
        for (x in dir) {
          if (system("test ! -e \"" dir[x] "\"" )) {
            delete dir[x]
          }
        }
        for (x in dir) {
          system("mkdir -p \"" dir[x] "\"" )
          system("chmod 750 \"" dir[x] "\"" )
          system("chown \"" user "\":\"" group "\" \"" dir[x] "\"" )
        }
      }
    '

  config_get options general options

  procd_open_instance
  # starting with full path seems cleaner judging by 'ps' output
  procd_set_param command $COMMAND
  # need to specify all or none of -conf, -log, and -db
  procd_append_param command \
    -cache "$dir_cache" \
    -conf "$dir_etc" \
    -db "$dir_db" \
    -g "$group" \
    -log "$dir_log" \
    -recordings "$dir_recordings" \
    -run "$dir_run" \
    -storage "$dir_storage" \
    -temp "$dir_temp" \
    -u "$user" \
    $options \
    -c
  # forward stderr to logd
  procd_set_param stderr $log_stderr
  # same for stdout
  procd_set_param stdout $log_stdout
  procd_close_instance
}

